package com.wsoft.cms.manager;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wsoft.cms.entity.CmsAnnouncementFileEntity;
import com.wsoft.cms.mapper.CmsAnnouncementFileMapper;
import com.wsoft.constant.redis.RedisKeyConstant;
import com.wsoft.core.annotation.GetRedisCache;
import com.wsoft.core.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author z001
 * @Date 2024/11/27 10:42
 */
@Slf4j
@Service
public class CmsAnnouncementFileManager extends ServiceImpl<CmsAnnouncementFileMapper, CmsAnnouncementFileEntity> {

    @Resource
    private RedisService redisService;

    /**
     * 批量保存
     * @param annoId
     * @param fileList
     */
    public void saveBatch(Long annoId,List<String> fileList){
        if(CollUtil.isEmpty(fileList)){
            return;
        }
        List<CmsAnnouncementFileEntity> list = new ArrayList<>();
        for (int i = 0; i < fileList.size(); i++) {
            CmsAnnouncementFileEntity fileEntity = new CmsAnnouncementFileEntity();
            fileEntity.setAnnoId(annoId);
            fileEntity.setFile(fileList.get(i));
            fileEntity.setSort(i);
            list.add(fileEntity);
        }
        super.saveBatch(list);
    }


    /**
     * 根据annoId 查询
     * @param annoId
     * @return
     */
    @GetRedisCache(type = RedisKeyConstant.Cms.CMS_ANNO_FILE_INFO,
            expire_sec = RedisKeyConstant.Cms.EXPIRED,
            value = RedisKeyConstant.REDIS_SELF)
    public List<CmsAnnouncementFileEntity>  getByAnnoId(Long annoId){
        QueryWrapper<CmsAnnouncementFileEntity> query = new QueryWrapper<>();
        query.lambda().eq(CmsAnnouncementFileEntity::getAnnoId,annoId)
                .orderByAsc(CmsAnnouncementFileEntity::getSort);
        return list(query);
    }

    /**
     * 更新文章 附件
     * @param annoId
     * @param fileList
     */
    public void updateBatch(Long annoId,List<String> fileList){
        //删除附件
        this.delByAnnoId(annoId);
        //新增新附件
        this.saveBatch(annoId,fileList);
    }


    /**
     * 根据annoId 删除
     * @param annoId
     * @return
     */
    public boolean delByAnnoId(Long annoId){
        QueryWrapper<CmsAnnouncementFileEntity> query = new QueryWrapper<>();
        query.lambda().eq(CmsAnnouncementFileEntity::getAnnoId,annoId);
        boolean b = remove(query);
        if(b){
            redisService.del(RedisKeyConstant.Cms.CMS_ANNO_FILE_INFO + annoId);
        }
        return b;
    }

}
